﻿using System.Configuration;
using System.Threading.Tasks;
using System.Web;
using Ipmce.RemoteVoting.Backend.DataAccess;
using Ipmce.RemoteVoting.Backend.SmsGateway.Processing;
using Ipmce.RemoteVoting.Backend.SmsGateway.Utils;
using Microsoft.Practices.Unity;

namespace Ipmce.RemoteVoting.Backend.SmsGateway
{
	public class HttpHandler : IHttpHandler
	{
		public void ProcessRequest(HttpContext context)
		{
			using (var container = new UnityContainer())
			{
				container.RegisterType<IRequestProcessor, RequestProcessor>()
					.RegisterType<IVoterSmsInfoParser, VoterSmsInfoParser>()
					.RegisterType<ISmsConfirmationGenerator, SmsConfirmationGenerator>()
					.RegisterType<IVoterRepository, VoterRepository>()
					.RegisterType<RemoteVotingContext>(new InjectionFactory
					                                   	(c =>
					                                   	 new RemoteVotingContext(
					                                   	 	ConfigurationManager.AppSettings["RemoteVotingDataBase"])));
				var processor = container.Resolve<IRequestProcessor>();
				var result = processor.ProcessSmsCode(context.Request["text"]);
				var responseTask = new Task(() => ResponseSms(context.Request["phone"], result));
				responseTask.Start();
			}
		}

		private static void ResponseSms(string number, string text)
		{
			var sender = new SmsSender(ConfigurationManager.AppSettings["SmsServerAddress"]);
			sender.Send(number, text);
		}

		public bool IsReusable
		{
			get { return true; }
		}
	}
}